package com.tzkyzj.tiremanager.service;

import com.tzkyzj.tiremanager.dto.LoginRequest;
import com.tzkyzj.tiremanager.dto.LoginResponse;
import com.tzkyzj.tiremanager.dto.UserInfo;
import com.tzkyzj.tiremanager.entity.User;
import com.tzkyzj.tiremanager.entity.UserSession;
import com.tzkyzj.tiremanager.repository.UserRepository;
import com.tzkyzj.tiremanager.repository.UserSessionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.UUID;

@Service
public class AuthService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserSessionRepository userSessionRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Transactional
    public LoginResponse login(LoginRequest loginRequest, String ipAddress, String userAgent) {
        LoginResponse response = new LoginResponse();

        // 验证用户
        User user = userRepository.findByUsername(loginRequest.getUsername())
                .orElse(null);

        if (user == null) {
            response.setSuccess(false);
            response.setMessage("用户不存在");
            return response;
        }

        if (!user.getEnabled()) {
            response.setSuccess(false);
            response.setMessage("用户已被禁用");
            return response;
        }

        // 调试信息：打印密码比较
        System.out.println("登录尝试 - 用户名: " + loginRequest.getUsername());
        System.out.println("输入密码: " + loginRequest.getPassword());
        System.out.println("数据库密码: " + user.getPassword());

        // 检查密码是否匹配
        boolean passwordMatches = checkPassword(loginRequest.getPassword(), user.getPassword(), user.getUsername());
        System.out.println("密码匹配: " + passwordMatches);

        if (!passwordMatches) {
            response.setSuccess(false);
            response.setMessage("密码错误");
            return response;
        }

        // 生成token
        String token = generateToken();

        // 创建会话
        UserSession session = new UserSession();
        session.setUser(user);
        session.setToken(token);
        session.setDeviceType(UserSession.DeviceType.valueOf(loginRequest.getDeviceType()));
        session.setLoginTime(LocalDateTime.now());
        session.setLastActivityTime(LocalDateTime.now());
        session.setExpiryTime(LocalDateTime.now().plusDays(7)); // 7天有效期
        session.setIpAddress(ipAddress);
        session.setUserAgent(userAgent);

        userSessionRepository.save(session);

        // 构建响应
        response.setSuccess(true);
        response.setMessage("登录成功");
        response.setToken(token);
        response.setUserInfo(buildUserInfo(user));

        return response;
    }

    /**
     * 检查密码是否匹配
     * 处理混合密码情况：admin用户是明文，其他用户是加密密码
     */
    private boolean checkPassword(String inputPassword, String storedPassword, String username) {
        // 如果是admin用户，使用明文比较
        if ("admin".equals(username)) {
            boolean matches = inputPassword.equals(storedPassword);
            System.out.println("admin用户明文比较结果: " + matches);
            return matches;
        }

        // 对于其他用户，使用PasswordEncoder验证
        try {
            boolean matches = passwordEncoder.matches(inputPassword, storedPassword);
            System.out.println("BCrypt验证结果: " + matches);
            return matches;
        } catch (Exception e) {
            // 如果验证失败，可能是其他加密方式或者是明文
            System.out.println("BCrypt验证异常，尝试其他验证方式: " + e.getMessage());

            // 如果存储的密码看起来不像BCrypt格式，尝试直接比较
            if (!storedPassword.startsWith("$2a$") && !storedPassword.startsWith("$2b$")) {
                boolean matches = inputPassword.equals(storedPassword);
                System.out.println("明文比较结果: " + matches);
                return matches;
            }

            return false;
        }
    }

    @Transactional
    public boolean logout(String token) {
        UserSession session = userSessionRepository.findByToken(token).orElse(null);
        if (session != null) {
            userSessionRepository.delete(session);
            return true;
        }
        return false;
    }

    public User validateToken(String token) {
        if (token == null || token.trim().isEmpty()) {
            return null;
        }

        UserSession session = userSessionRepository.findByToken(token).orElse(null);
        if (session == null || session.getExpiryTime().isBefore(LocalDateTime.now())) {
            return null;
        }

        // 更新最后活动时间
        session.setLastActivityTime(LocalDateTime.now());
        userSessionRepository.save(session);

        return session.getUser();
    }

    /**
     * 根据用户名获取用户信息
     */
    public User getUserByUsername(String username) {
        return userRepository.findByUsername(username).orElse(null);
    }

    /**
     * 根据用户ID获取用户信息
     */
    public User getUserById(Long userId) {
        return userRepository.findById(userId).orElse(null);
    }

    /**
     * 验证用户密码
     */
    public boolean validatePassword(String username, String password) {
        User user = getUserByUsername(username);
        if (user == null || !user.getEnabled()) {
            return false;
        }
        return checkPassword(password, user.getPassword(), username);
    }

    /**
     * 更新用户最后登录时间
     */
    @Transactional
    public void updateLastLoginTime(String username) {
        User user = getUserByUsername(username);
        if (user != null) {
            user.setUpdatedTime(LocalDateTime.now());
            userRepository.save(user);
        }
    }

    /**
     * 检查用户是否有权限访问特定资源
     */
    public boolean hasPermission(User user, String resource) {
        if (user == null) return false;

        // 根据用户角色判断权限
        switch (user.getRole()) {
            case ADMIN:
                return true; // 管理员有所有权限
            case COMPANY:
                // 公司用户只能访问公司相关资源
                return resource.startsWith("/api/tires") ||
                        resource.startsWith("/tire-") ||
                        resource.equals("/dashboard");
            case DRIVER:
                // 司机只能访问有限的资源
                return resource.startsWith("/api/tires") &&
                        !resource.contains("/batch-add") &&
                        !resource.contains("/add") &&
                        !resource.equals("/user-management");
            default:
                return false;
        }
    }

    /**
     * 加密密码（用于创建或更新用户时使用）
     */
    public String encodePassword(String rawPassword) {
        return passwordEncoder.encode(rawPassword);
    }

    /**
     * 检查密码是否需要重新加密（从明文转为加密）
     */
    public boolean needsReencoding(String storedPassword, String username) {
        // admin用户保持明文，其他用户如果还是明文则需要加密
        return !"admin".equals(username) &&
                !storedPassword.startsWith("$2a$") &&
                !storedPassword.startsWith("$2b$");
    }

    private String generateToken() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    private UserInfo buildUserInfo(User user) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());
        userInfo.setUsername(user.getUsername());
        userInfo.setRole(user.getRole().name());
        userInfo.setTransportCompany(user.getTransportCompany());
        userInfo.setVehiclePlateNumber(user.getVehiclePlateNumber());
        return userInfo;
    }
}